package com.example.mvc.controller;

import com.example.mvc.bean.User;
import com.example.mvc.service.UserService;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;

@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
    private UserService userService = new UserService();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

      //获取用户输入的用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);

        // 获取用户输入的验证码
        //用户输入的验证码
        String checkCode = req.getParameter("checkCode");

        // 程序生成的验证码，从Session获取
        HttpSession session = req.getSession();
        String checkCodeGen = (String) session.getAttribute("checkCodeGen");

        // 比对
        if(!checkCodeGen.equalsIgnoreCase(checkCode)){

            req.setAttribute("register_msg","验证码错误");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
            // 不允许注册
            return;
        }

        //注册
        boolean isCanRegister = userService.register(user);

        if (isCanRegister){//要注册的用户存在可以注册，
            req.setAttribute("register_msg","注册成功");
            //注册成功，调到登录界面，并提示注册成功
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
        }else {
            req.setAttribute("register_msg","用户已经存在");
            req.getRequestDispatcher("/register.jsp").forward(req,resp);
        }






    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
